package com.dingpeikeji.quickdeer.modules.wx.rentprocut.web;

import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.modules.wx.common.web.OAuth;
import com.google.common.collect.Lists;

/**
 * 微信端整车订票
 */
@Controller
@RequestMapping("wx/pu/rentproduct")
public class WxRentproductController extends BaseController{
	
	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private TCargotypeService tCargotypeService;
	@Autowired
	private TRentgroupService tRentgroupService;
	
	/**
	 * 查询页
	 */
	@RequestMapping("query")
	public String query(TRentproduct tRentproduct, Model model) throws ParseException {
		// 消息集合
		List<String> messages = Lists.newArrayList();
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model)
				// 包车天数为空，1天-10天选择，默认1天
				.handleDaysnum();
		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if(warningFor2Hours != null){
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}
		addMessage(model, messages.toArray(new String[]{}));
		// 历史日期和时间不可选
		Calendar calendar = Calendar.getInstance();
		model.addAttribute("oldDateStr", MessageFormat.format("new Date({0},{1},{2})",""+calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)));
		// TODO 暂时不考虑历史时间
		model.addAttribute("oldTimeStr","");
		model.addAttribute("tRentproduct",tRentproduct);
		// 视图
		String viewPage = "wx/modules/rentproduct/queryFor{0}Rent";
		return MessageFormat.format(viewPage, rentproductService.getRentTypeName(tRentproduct.getRentType()));
	}
	
	/**
	 * 整车预订列表页
	 */
	@RequestMapping("list")
	public String list(TRentproduct tRentproduct,HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
		String viewPage = "wx/modules/rentproduct/listFor{0}Rent"; // 视图
		
		// 数据校验
		
		// 消息集合
		List<String> messages = Lists.newArrayList();
		
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model)
				// 包车天数为空，1天-10天选择，默认1天
				.handleDaysnum();
		
		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if(warningFor2Hours != null){
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}
		
		// 根据包车天数计算租赁结束日期
		String warningFor3Month = tRentproduct.handle3MonthWarning();
		if(warningFor3Month != null){
			messages.add(warningFor3Month);
		}
		
		// 出发地和目的地的校验逻辑
		
		if(tRentproduct.getDepartcity()==null ||
				ValidateTool.isEmptyOrNull(tRentproduct.getDepartcity().getSiteid()) ||
				ValidateTool.isEmptyOrNull(tRentproduct.getDepartcity().getSitename())) {
			messages.add("请选择出发地");
		}
		if((tRentproduct.getRentType().equals(TOrders.ORDER_TYPE_RENTPRODUCT_DAY) && tRentproduct.getTabType().equals("跨市") && 
				(tRentproduct.getDestcity()==null ||
					ValidateTool.isEmptyOrNull(tRentproduct.getDestcity().getSiteid()) ||
					ValidateTool.isEmptyOrNull(tRentproduct.getDestcity().getSitename())
				)
			) || (tRentproduct.getRentType().equals(TOrders.ORDER_TYPE_RENTPRODUCT_TRAVEL) && 
						(tRentproduct.getDestcity()==null ||
							ValidateTool.isEmptyOrNull(tRentproduct.getDestcity().getSiteid()) ||
							ValidateTool.isEmptyOrNull(tRentproduct.getDestcity().getSitename())
						)
				) ) {
			messages.add("请选择目的地");
		}
		
		// 当前下午2点停止卖票
		if(messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if(warningFor14Hours != null){
				messages.add(warningFor14Hours);
			}
		}
		
		// 日期选择数据，上一天、下一天
		rentproductService.changeDate(request, model, tRentproduct.getFromdate());
		
		if(messages.isEmpty()){
			
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(tRentproduct, request ,"wx");
			
			// 分页对象
			Page<TRentproduct> page = new Page<TRentproduct>(request, response);
			tRentproduct.setPage(page);
			// 整车查询列表
			List<TRentproduct> rentproductList = null;
			// 市内日租包车
			if(TOrders.ORDER_TYPE_RENTPRODUCT_DAY.equals(tRentproduct.getRentType()) && tRentproduct.getTabType().equals("市内")) {
				rentproductList = rentproductService.findInCityListWX(tRentproduct);
			}
			// 跨城日租包车
			if(TOrders.ORDER_TYPE_RENTPRODUCT_DAY.equals(tRentproduct.getRentType()) && tRentproduct.getTabType().equals("跨市")) {
				rentproductList = rentproductService.findBetweenCityListWX(tRentproduct);
			}
			// 旅游包车
			if(TOrders.ORDER_TYPE_RENTPRODUCT_TRAVEL.equals(tRentproduct.getRentType())) {
				rentproductList = rentproductService.findTravelListWX(tRentproduct);
			}
			// 接送机
			if(TOrders.ORDER_TYPE_RENTPRODUCT_AIRPLANE.equals(tRentproduct.getRentType())) {
				rentproductService.switchCity(tRentproduct);
				rentproductList = rentproductService.findPlaneListWX(tRentproduct);
				rentproductService.switchCity(tRentproduct);
			}
			// 接送火车
			if(TOrders.ORDER_TYPE_RENTPRODUCT_TRAIN.equals(tRentproduct.getRentType())) {
				rentproductService.switchCity(tRentproduct);
				rentproductList = rentproductService.findTrainList(tRentproduct);
				rentproductService.switchCity(tRentproduct);
			}
			page.setList(rentproductList);
			model.addAttribute("page", page);
		} else {
			addMessage(model, messages.toArray(new String[]{}));
		}
		// 车型数据
		List<TCargotype> cargotypeList = null;
		// 服务商数据
		List<Office> officeList = null;
		if (TOrders.ORDER_TYPE_RENTPRODUCT_TRAIN.equals(tRentproduct.getRentType()) ||
				TOrders.ORDER_TYPE_RENTPRODUCT_AIRPLANE.equals(tRentproduct.getRentType())	) {
			officeList = rentproductService.findCityBusServer(tRentproduct.getDestcity().getSiteid());
			cargotypeList = tCargotypeService.findCityCargoList(tRentproduct.getDestcity().getSiteid());
		} else {
			officeList = rentproductService.findCityBusServer(tRentproduct.getDepartcity().getSiteid());
			cargotypeList = tCargotypeService.findCityCargoList(tRentproduct.getDepartcity().getSiteid());
		}
		
		model.addAttribute("cargotypeList", cargotypeList);
		model.addAttribute("officeList", officeList);
		model.addAttribute("tRentproduct", tRentproduct);
		String format = MessageFormat.format(viewPage, rentproductService.getRentTypeName(tRentproduct.getRentType()));
		return format;
	}
	
	/**
	 * 整车预定详情页
	 */
	@RequestMapping("details")
	public String details(TRentproduct tRentproduct, Model model, HttpServletRequest request) throws Exception{
		String viewPage = "wx/modules/rentproduct/detailFor{0}Rent"; // 视图
		
		// 根据ID查询选中的整车信息
		TRentproduct rentproduct = tRentproductService.get(tRentproduct.getRentid());
		TRentgroup rentgroup = tRentgroupService.get(rentproduct.getRentgrpid());
		
		if(rentproduct !=null ){
			
			// 协议价逻辑处理
			
			TRentproduct query = new TRentproduct();
			query.setRentid(tRentproduct.getRentid());
			query.setDepartdate(DateUtils.parseDate(tRentproduct.getFromdateStr() + " " + tRentproduct.getTime()));
			
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request,"wx");
			query = rentproductService.getSuitrtnprice(query);
			rentproduct.setSuitrtnprice(query.getSuitrtnprice());
		}
		
		// 数据校验
		
		// 消息集合
		List<String> messages = Lists.newArrayList();
		
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		
		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if(warningFor2Hours != null){
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}
		
		// 当前下午2点停止卖票
		if(messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if(warningFor14Hours != null){
				messages.add(warningFor14Hours);
			}
		}
		
		if(!messages.isEmpty()){
			addMessage(model, messages.toArray(new String[]{}));
		}
		
		model.addAttribute("tRentproduct", rentproduct);
		model.addAttribute("rentgroup", rentgroup);
		model.addAttribute("query", tRentproduct);
		String format = MessageFormat.format(viewPage, rentproductService.getRentTypeName(tRentproduct.getRentType()));
		return format;
	}

	/**
	 * 生成订单
	 */
	@RequestMapping("booking")
	public String booking(TOrders orders,Model model,RedirectAttributes redirectAttributes, HttpServletRequest request) throws ParseException{
		String redirctPage = "redirect:/wx/pu/rentproduct/details?repage&time={0}&daysnum={1}&rentid={2}&rentType={3}&fromdateStr={4}"; // 订单信息页
		String payWayPage = "redirect:/wx/pay/payWay?orderid={0}"; // 支付方式选择页
		
		User user = (User)request.getSession().getAttribute(OAuth.SESSION_PUBUSER);
		orders.setOrderuserid(user.getId());

		// 校验数据
		
		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		if(ValidateTool.isEmptyOrNull(orders.getPurchasenum())){
			messages.add("请填写车辆数");
		} else if (!ValidateTool.isNonnegativeDigit(orders.getPurchasenum())) {
			messages.add("车辆数量不正确");
		}
		if(ValidateTool.isEmptyOrNull(orders.getBoardaddr())){
			messages.add("请填写上车地点");
		}
		if(ValidateTool.isEmptyOrNull(orders.getContacts())){
			messages.add("请填写联系人姓名");
		}
		if(ValidateTool.isEmptyOrNull(orders.getOrdertype())){
			messages.add("未知用途的订单");
		}
		if(ValidateTool.isEmptyOrNull(orders.getPayertel())){
			messages.add("请填写联系电话");
		} else if(!ValidateTool.isMobile(orders.getPayertel())) {
			messages.add("电话号码不正确");
		}
		
		TRentproduct tRentproduct = new TRentproduct();
		tRentproduct.setFromdateStr(orders.getFromdateStr());
		tRentproduct.setTime(orders.getTime());
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		
		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if(warningFor2Hours != null){
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}

		// 当前下午2点停止卖票
		if(messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if(warningFor14Hours != null){
				messages.add(warningFor14Hours);
			}
		}

		if(messages.isEmpty()) {
			// 协议价逻辑处理
			
			TRentproduct query = new TRentproduct();
			query.setRentid(Integer.parseInt(orders.getRealscheid()));
			query.setDepartdate(DateUtils.parseDate(orders.getDepartdateStr()));
			
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request,"wx");
			query = rentproductService.getSuitrtnprice(query);
			orders.setDueamount(""+query.getSuitrtnprice());
			Integer purchasenum = Integer.valueOf(orders.getPurchasenum());
			if(orders.getOrdertype().equals(TOrders.ORDER_TYPE_RENTPRODUCT_DAY)){
				orders.setDueamount(""+query.getSuitrtnprice()*orders.getBookingdays()*purchasenum);
			} else {
				orders.setDueamount(""+query.getSuitrtnprice()*purchasenum);
			}
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				if(pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					return MessageFormat.format(payWayPage, orderid.toString());
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("orders", orders);
		addMessage(redirectAttributes, messages.toArray(new String[]{}));
		
		if (orders.getBookingdays() == null)
			orders.setBookingdays(1);
		
		return MessageFormat.format(redirctPage, orders.getTime(), orders.getBookingdays().toString(), orders.getRealscheid().toString(), orders.getOrdertype(), orders.getFromdateStr());
	}

}
